package com.seres.aop;

import com.alibaba.fastjson.JSONObject;
import com.seres.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description : 监控所有controller
 * @ClassName : ControllerMonitorAop
 * @Author : 程磊
 * @Date: 2020-07-24 15:48
 */
@Aspect
@Configuration
@Slf4j
public class ControllerMonitorAop {
    /*@Pointcut("execution(* com.seres..*.controller..*(..))")
    public void excudeService() {}

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String ipAddr =getIpAddr (request);
        String url = request.getRequestURL().toString();
        Enumeration<String> enumeration = request.getHeaderNames();
        Map<String,Object> headers = new HashMap<>();
        while (enumeration.hasMoreElements()){
            String headerName = enumeration.nextElement();
            if(StringUtils.equals(headerName,"source")){
                headers.put(headerName,request.getHeader(headerName));
            }else if(StringUtils.equals(headerName,"userid")){
                headers.put(headerName,request.getHeader(headerName));
            }else if(StringUtils.equals(headerName,"assetId")){
                headers.put(headerName,request.getHeader(headerName));
            }
        }
        long time = System.currentTimeMillis();
        // result的值就是被拦截方法的返回值
        try {
            Object result = pjp.proceed();
            log.info("\nip:{} \nurl:{}\nheader:{}\nparams:{}\nresult:{}\ntime:{} ms", ipAddr, url, headers, JSONObject.toJSONString(request.getParameterMap()), result != null ? JSONObject.toJSONString(result) : "", System.currentTimeMillis() - time);
            return result;
        }catch (Throwable e){
            log.info("\nip:{} \nurl:{}\nheader:{}\nparams:{}\nresult:{}\ntime:{} ms", ipAddr, url, headers, JSONObject.toJSONString(request.getParameterMap()),"", System.currentTimeMillis() - time);
            log.error("{}",e);
            throw e;
        }
    }*/
    /**
     * 请求参数拼装
     * @param paramsArray
     * @return
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                params += JSONObject.toJSONString(paramsArray[i])+" ";
            }
        }
        return params.trim();
    }

    /**
     * 获取登录用户的IP地址
     *
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "本地";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
